<template>
  <el-drawer :visible.sync="drawer" direction="rtl" size="50%" :with-header="false" :width="700">
    <div class="drawer_box">
      <div class="drawer_title">
        <div class="drawer_t">
          <div class="drawer_t_l">
            <img class="drawer_t_l_img" src="/static/skin/herodoo/main/platform/home/img/piliangoumai.png" alt="" />
            查看投票
          </div>
          <img class="drawer_t_r" src="/static/skin/herodoo/main/platform/home/img/guanbi.png" alt=""
            @click="drawer = false" />
        </div>
      </div>
      <div class="drawer_content">
        <text>基本信息</text>
        <div class="list-box">
          <div class="left">投票标题:</div>
          <div class="right">
            {{ form.headline }}
          </div>
        </div>
        <div class="list-box">
          <div class="left">浏览量(次):</div>
          <div class="right">
            {{ form.PvCount }}
          </div>
        </div>
        <div class="list-box">
          <div class="left">投票情况:</div>
          <div class="right">
            <div class="tp" v-for="(item, index) in list" :key="item.ID">
              <div class="names">选项{{ index + 1 }}:<span @click="openDetail(item, index, true)">{{ item.Name }}</span>
              </div>
              <div class="row">
                <el-progress class="progress" :percentage="(totle == 0
                  ? 0
                  : (item.VoteOptionNumber / totle) * 100
                ).toFixed(2)
                  " :show-text="false"></el-progress>
                {{ item.VoteOptionNumber }} 票 ({{
                  totle == 0
                    ? 0
                    : ((item.VoteOptionNumber / totle) * 100).toFixed(2)
                }}%)
              </div>
            </div>
          </div>
        </div>
        <div class="list-box">
          <div class="left">投票时间:</div>
          <div class="right">
            <span style="margin-right: 20px;" v-for="item in cutOffTiem" :key="item">
              {{ item }}
            </span>
          </div>
        </div>
        <div class="list-box" v-if="form.fileList[0]">
          <div class="left">图片:</div>
          <div class="right">
            <img class="objectfit" style="width: 450px; height: 300px;" :src="form.fileList[0].url" alt="" />
          </div>
        </div>
        <div class="list-box">
          <div class="left">投票说明:</div>
          <div class="right">
            <div v-html="form.deltedContent"></div>
          </div>
        </div>
        <div class="desc">
          <!-- <quill ref="quill" :octopus="octopus" @quillContent="getQuillContent" :desc="form.deltedContent"
            :isEdit="!['CREATE', 'UPDATE'].includes(isEdit)" :key="getQuillContent"></quill> -->
        </div>
        <div class="list-box">
          <div class="left">选项类型:</div>
          <div class="right" style="width: 90%;">
            <el-select v-model="value" placeholder="请选择" disabled>
              <el-option v-for="item in Select" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <div class="optionBox">
              <div class="optionList" v-for="(item, index) in SelectArr" :key="item.id">
                <div style="width: 10%;">
                  <div>选项:{{ index + 1 }}</div>
                </div>
                <div style="width: 90%;">
                  <div @click="openDetail(item)" class="name">{{ item.name }}</div>
                  <!-- <el-input placeholder="请输入选项名称" v-model="item.name" clearable>
                  </el-input> -->
                  <div>{{ item.textarea }}</div>
                  <!-- <el-input style="margin: 20px 0;" type="textarea" placeholder="请输入描述内容" v-model="item.textarea"
                    maxlength="100" show-word-limit>
                  </el-input> -->
                  <div>
                    <div style="display: flex;" v-if="value == 2">
                      <img class="objectfit" style="width: 450px; height: 300px;" v-for="item in item.Image" :key="item"
                        :src="item.url" alt="" />
                    </div>
                    <div style="display: flex;" v-if="value == 4">
                      <video style="width: 450px; height: 300px;" controls v-for="item in item.video" :key="item"
                        :src="item.url"></video>
                    </div>
                    <div style="display: flex;" v-if="value == 3">
                      <audio controls v-for="item in item.audio" :key="item" :src="item.url"></audio>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="list-box">
          <div class="left">是否允许多选:</div>
          <div class="right">
            <el-radio disabled v-model="multipleChoice" label="1">是</el-radio>
            <el-radio disabled v-model="multipleChoice" label="0">否</el-radio>
          </div>
        </div>
        <div class="list-box">
          <div class="left">展示类型:</div>
          <div class="right">
            <el-radio disabled v-model="resultsDisplay" label="1">投票前显示</el-radio>
            <el-radio disabled v-model="resultsDisplay" label="2">投票后显示</el-radio>
            <el-radio disabled v-model="resultsDisplay" label="3">始终不显示</el-radio>
          </div>
        </div>
        <div class="list-box">
          <div class="left">是否发布:</div>
          <div class="right">
            <el-radio disabled v-model="publishStatus" label="1">是</el-radio>
            <el-radio disabled v-model="publishStatus" label="0">否</el-radio>
          </div>
        </div>
      </div>

      <div class="button_list">
        <button @click="chanle()" v-if="publishStatus == 1" style="background-color: #343434;color:#fff;">
          撤销发布
        </button>
        <button v-if="isEdit != 'look'" @click="save()">保存</button>
      </div>
    </div>
    <detail ref="detail" :messageList="form"></detail>
  </el-drawer>
</template>

<script>
import imgUplode from "@/components/Components/imgUpdate.vue";
import quill from "@/components/Components/quillEditor.vue";
import FileUpdate from "../../Components/FileUpdate.vue";
import detail from "./detail.vue";
export default {
  components: {
    quill,
    FileUpdate,
    imgUplode,
    detail
  },
  name: "cat_dialog",
  props: {
    isEdit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      cutOffTiem: [],
      multipleChoice: "0",
      resultsDisplay: "2",
      publishStatus: "0",
      octopus: this.$parent.octopus,
      drawer: false,
      isEdit: "look",
      form: {
        ID: 1,
        StartTime: "",
        EndTime: "",
        fileList: [],
        headline: "",
        deltedContent: "",
        PvCount: 0
      },
      value: "1",
      Select: [
        {
          value: "1",
          label: "文本"
        },
        {
          value: "2",
          label: "文本+图片"
        },
        {
          value: "3",
          label: "文本+音频"
        },
        {
          value: "4",
          label: "文本+视频"
        }
      ],
      SelectArr: [
        {
          id: 1,
          name: "",
          Image: [],
          video: [],
          audio: [],
          textarea: "",
          Attachment: []
        }
      ],
      list: [],
      totle: 0
    };
  },
  created() { },
  watch: {
    cutOffTiem(newValue) {
      this.form.StartTime = newValue[0];
      this.form.EndTime = newValue[1];
    }
  },
  methods: {
    deleteRefund(index) {
      this.SelectArr.splice(index, 1);
    },
    addSelect() {
      let ArrLength = this.SelectArr.length;
      const newRefundType = {
        id: ArrLength++,
        name: "",
        Image: [],
        video: [],
        audio: [],
        textarea: "",
        Attachment: []
      };
      // 将新对象添加到数组中
      this.SelectArr.push(newRefundType);
    },
    // FileListEv(){
    //   this.$set(this.SelectArr[index].fileList, 0, fileList[0]);
    // },
    getSelectArr(fileList, index, type) {
      if (fileList.length == 0) {
        this.$set(this.SelectArr[index], type, []);
      } else {
        this.$set(this.SelectArr[index][type], 0, fileList[0]);
      }
    },
    getImgsUrl(fileList) {
      this.form.fileList = fileList;
      // this.$set(this.form.fileList, 0, fileList[0]);
    },
    getQuillContent(e) {
      this.form.deltedContent = e;
    },
    drawerOpen(data = null, type = "CREATE") {
      // editType 是否可编辑，打他 父级传的数据，type  是新建还是更新
      this.drawer = true;
      this.isEdit = type;
      if (this.isEdit == "CREATE") {
        this.cutOffTiem = [];
        this.form = {
          ID: 1,
          StartTime: "",
          EndTime: "",
          fileList: [],
          headline: "",
          deltedContent: "",
          PvCount: 0
        };
        this.SelectArr = [
          {
            id: 1,
            name: "",
            Image: [],
            video: [],
            audio: [],
            textarea: "",
            Attachment: []
          }
        ];
      }
      if (this.isEdit == "UPDATE" || this.isEdit == "look") {
        this.form.ID = data.ID;
        this.form.headline = data.Name;
        this.$set(this.cutOffTiem, 0, data.StartTime);
        this.$set(this.cutOffTiem, 1, data.EndTime);
        this.form.fileList = JSON.parse(data.PicturePath);
        this.form.deltedContent = data.Description;
        this.form.PvCount = data.PvCount;
        this.value = `${data.VoteOptionTypeID}`;
        this.multipleChoice = `${data.IsMultipleChoice}`;
        this.resultsDisplay = `${data.VoteTypeID}`;
        this.publishStatus = `${data.IsRelease}`;
        this.gitDetailedList(data.ID);
        this.api_1363(data.ID);
      }
    },
    save() {
      let isValid = true;
      if (!this.form.headline) {
        this.$message.error("请完善标题");
      } else if (!this.form.StartTime && !this.form.EndTime) {
        this.$message.error("请完善投票截止日期");
      } else if (this.form.fileList.length == 0) {
        this.$message.error("请上传投票图片");
      } else if (!this.form.deltedContent) {
        this.$message.error("请完善投票说明");
      } else {
        for (const [index, item] of this.SelectArr.entries()) {
          if (item.name.trim() == "" || item.textarea.trim() == "") {
            isValid = false;
            this.$message.error(`序号 ${index + 1} 的名称或描述不能为空`);
            return;
          } else if (item.Image.length == 0 && this.value == 2) {
            isValid = false;
            this.$message.error(`序号 ${index + 1} 的图片不能为空`);
            return;
          } else if (item.audio.length == 0 && this.value == 3) {
            isValid = false;
            this.$message.error(`序号 ${index + 1} 的音频不能为空`);
            return;
          } else if (item.video.length == 0 && this.value == 4) {
            isValid = false;
            this.$message.error(`序号 ${index + 1} 的视频不能为空`);
            return;
          }
        }
        if (isValid) {
          this.update_api_1345();
        }
      }
    },
    update_api_1345() {
      let this_ = this;
      this.octopus.request.api.post(
        "/Octopus/Engine/Item",
        {
          id: 1345,
          type: this_.isEdit,
          value: this.isEdit == "UPDATE" ? this.form.ID : "",
          cellData: [
            { name: "CreateUserID", defaultValue: this_.octopus.passport.id }, // 创建人
            { name: "Description", defaultValue: this_.form.deltedContent }, // 投票内容
            { name: "EndTime", defaultValue: this_.form.EndTime }, // 结束时间
            { name: "ID" }, // ID
            { name: "IsMultipleChoice", defaultValue: this_.multipleChoice }, // 是否多选（0单选  1多选）
            { name: "VoteTypeID", defaultValue: this_.resultsDisplay }, // 投票是否公开（0不  1是）（用户投票完成是否可以直接看到所选的选项的票数  ）
            { name: "IsRelease", defaultValue: "0" }, // 是否发布(0不  1发布)
            { name: "Name", defaultValue: this_.form.headline }, // 投票标题
            { name: "OptionNumber" }, // 可选数量
            {
              name: "PicturePath",
              defaultValue: JSON.stringify(this_.form.fileList)
            }, // 图片
            { name: "StartTime", defaultValue: this_.form.StartTime }, // 开始时间
            { name: "VoteOptionTypeID", defaultValue: this_.value } // 投票选项内容（1图文  2音频）
          ]
        },
        data => {
          if (data.status.code == 200) {
            let queue = [];
            this_.SelectArr.map(item => {
              queue.push(this_.CRVoteItem(data.content.value, item));
            });
            Promise.all(queue).then(res => {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.drawer = false;
              this_.$emit("reload");
            });
          } else {
            this.octopus.tips.error(data);
          }
        }
      );
    },
    CRVoteItem(ID, data) {
      return new Promise((resolve, reject) => {
        if (this.value == 2) {
          data.Attachment = data.Image;
        }
        if (this.value == 3) {
          data.Attachment = data.audio;
        }
        if (this.value == 4) {
          data.Attachment = data.video;
        }
        let this_ = this;
        this.octopus.request.api.post(
          "/Octopus/Engine/Item",
          {
            id: 1346,
            type: this_.isEdit,
            value: this_.isEdit == "UPDATE" ? data.id : "",
            cellData: [
              {
                name: "Attachment",
                defaultValue: JSON.stringify(data.Attachment)
              }, // 附件（音频、视频）
              { name: "CreateUserID", defaultValue: this_.octopus.passport.id }, // 创建人
              { name: "Description", defaultValue: data.textarea }, // 选项内容（图文描述）
              { name: "Name", defaultValue: data.name }, // 选项名称
              { name: "VoteID", defaultValue: ID } // 投票表ID
            ]
          },
          data => {
            if (data.status.code == 200) {
              resolve(data);
            } else {
              this.octopus.tips.error(data);
              reject(data);
            }
          }
        );
      });
    },
    gitDetailedList(ID) {
      let this_ = this;
      this.octopus.request.api.post(
        "/Octopus/Engine/List",
        {
          id: 1346,
          cellData: [
            { name: "Attachment" }, // 附件（音频、视频）
            { name: "CreateTime" }, // 创建时间
            { name: "CreateUserID" }, // 创建人
            { name: "Description" }, // 选项内容（图文描述）
            { name: "ID" }, // ID
            { name: "Name" }, // 选项名称
            { name: "VoteID", filterKey: "=", filterValue: ID } // 投票表ID
          ]
        },
        data => {
          if (data.status.code == 200) {
            this.SelectArr = data.content.queryData.map(item => {
              return {
                id: item.ID,
                name: item.Name, // 如果有名称的字段可以赋值
                Image: this.value == "2" ? JSON.parse(item.Attachment) : [], // 图片等其他属性也可以赋值
                video: this.value == "4" ? JSON.parse(item.Attachment) : [],
                audio: this.value == "3" ? JSON.parse(item.Attachment) : [],
                textarea: item.Description,
                Attachment: JSON.parse(item.Attachment)
              };
            });
          } else {
            this.octopus.tips.error(data);
          }
        }
      );
    },
    // 获取投票情况
    api_1363(ID) {
      let this_ = this;
      this.octopus.request.api.post(
        "/Octopus/Engine/List",
        {
          id: 1363,
          cellData: [
            { name: "Attachment" }, // 附件（音频、视频）
            { name: "CreateTime" }, // CreateTime
            { name: "Description" }, // 选项内容（图文描述）
            { name: "ID" }, // ID
            { name: "Name" }, // 选项名称
            { name: "VoteID" }, // 投票表ID
            { name: "VoteOptionNumber" } // 选项票数
          ],
          paramData: {
            ID: ID
          }
        },
        data => {
          if (data.status.code == 200) {
            this.totle = 0;
            data.content.queryData.map(v => {
              this.totle += v.VoteOptionNumber;
            });
            this.list = data.content.queryData;
          } else {
            this.octopus.tips.error(data);
          }
        }
      );
    },

    chanle() {
      this.$confirm(`确定撤销发布这个投票吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // type: 'warning'
        center: true
      }).then(res => {
        this.api_1345();
      }).catch(() => {
        console.log('取消了');
      })
    },
    api_1345() {
      this.octopus.request.api.post(
        "/Octopus/Engine/Item",
        {
          id: 1345,
          type: "UPDATE",
          value: this.form.ID,
          cellData: [
            { name: "IsRelease", defaultValue: "0" } // 是否发布(0不  1发布)
          ]
        },
        data => {
          if (data.status.code == 200) {
            this.$emit("reload");
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.drawer = false;
          } else {
            this.octopus.tips.error(data);
          }
        }
      );
    },
    openDetail(item, index, is_top = false) {
      if (!is_top) {
        let find = this.list.find(x => x.ID == item.id);
        let findIndex = this.list.findIndex(x => x.ID == item.id);
        this.$refs.detail.drawerOpen(find, this.totle, findIndex + 1)
      } else {
        this.$refs.detail.drawerOpen(item, this.totle, index + 1)
      }

    }
  }
};
</script>
<style scoped>
.objectfit {
  object-fit: scale-down;
}

.optionList {
  display: flex;
  margin: 20px 0;
}

.drawer_box {
  padding: 3rem 0.8rem 3rem 0;
  height: calc(100% - 5rem);
  display: flex;
  flex-direction: column;
}

.drawer_title {
  box-shadow: 0px 5px 5px rgb(230 228 228 / 30%);
  padding-bottom: 1rem;
  font-size: 1.6rem;
}

.drawer_t {
  padding: 0 2.8rem;
  display: flex;
  justify-content: space-between;
}

.drawer_t_l {
  display: flex;
  align-items: center;
  font-size: 2rem;
  font-weight: bold;
}

.drawer_t_l_img {
  width: 2.8rem;
  margin-right: 1rem;
}

.drawer_t_r {
  width: 3rem;
  height: 3rem;
  cursor: pointer;
}

.button_box {
  margin-top: 1rem;
  padding: 0 3rem;
  display: flex;
}

.drawer_content {
  overflow-y: auto;
  margin-top: 1.5rem;
  height: calc(100vh - 11rem);
  padding: 0 3rem;
  width: 100%;
  padding-bottom: 1rem;
}

.drawer_content .title {
  font-size: 1.8rem;
  font-weight: bold;
}

.drawer_content .driver-title {
  margin-top: 1em;
}

.content-box {
  display: flex;
  align-items: center;
  margin: 2rem 0 2rem 2em;
}

.mt-10 {
  margin-top: 10rem;
}

.content-box .label {
  width: 25%;
  font-size: 1.6rem;
}

.content-box .label .label-bold {
  font-size: 1.8rem;
  font-weight: bold;
}

.content-box .desc {
  flex: 1;
  font-size: 1.6rem;
}

.list-box {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

.list-box {
  line-height: 4rem;
  margin-top: 2rem;
}

.list-box .left {
  width: 20%;
  font-size: 1.5rem;
}

.list-box .right {
  width: 80%;
}

.button_list {
  margin-top: 1rem;
  display: flex;
  justify-content: end;
  position: absolute;
  background-color: #ffff;
  bottom: 1rem;
  width: calc(100% - 7rem);
}

.button_list button {
  border: none;
  height: 4rem;
  width: 12rem;
  border-radius: 1rem;
  margin-left: 1rem;
  color: #ffff;
  background-color: #f78c53;
  cursor: pointer;
}

.tp .row {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.tp .progress {
  width: 80%;
}

.tp .names span {
  color: #409eff;
  cursor: pointer;
}

.optionList .name {
  color: #409eff;
  cursor: pointer;
}
</style>
